package com.lokyiu.mybible.wol;

import java.io.IOException;
import java.net.SocketTimeoutException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class UrlDocumentFactory implements DocumentFactory {
	public static final String WOL_NWT_URL = "http://wol.jw.org/en/wol/binav/r1/lp-e/nwt/E/2013";

	private String url;
	
	public UrlDocumentFactory() {
	}
	
	public UrlDocumentFactory(String url) {
		this.url = url;
	}
	
	public void setUrl(String url) {
		this.url = url;
	}
	@Override
	/**
	 * Uses the jsoup library to retrieve the DOM document.
	 * If the operation times out, it will retry 3 times.
	 * @param url
	 * @return
	 */
	public Document getDocument() {
		Document doc = null;
		try {
			doc = (Document) Jsoup.connect(url).get();
		} catch (SocketTimeoutException ste) {
			//Timed out, so retry 3 times
			System.err.println("Timed out, so retrying 1...");
			doc = retryGetDocument(url, 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}
	
	/**
	 * This method performs the retry.  Called from getDocument(String).
	 * DON'T call directly.
	 * @param url
	 * @param retryNo
	 * @return
	 */
	private Document retryGetDocument(String url, int retryNo) {
		Document doc = null;
		if (retryNo < 3) {
			try {
				doc = (Document) Jsoup.connect(url).get();
			} catch (SocketTimeoutException ste) {
				//Timed out again, so retry
				System.out.println("Timed out again, retry " + retryNo);
				doc = retryGetDocument(url, retryNo++);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("Retried 3 times, so aborting...");
		}
		return doc;
	}

}
